﻿using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace OnHook.Common.Extension
{
    /// <summary>
    /// HttpContent扩展方法
    /// </summary>
    public static class HttpContextExtension
    {

        /// <summary>
        /// 判断是否是Ajax请求
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public static bool IsAjax(this HttpRequest req)
        {
            bool result = false;

            var xreq = req.Headers.ContainsKey("x-requested-with");
            if (xreq)
            {
                result = req.Headers["x-requested-with"] == "XMLHttpRequest";
            }

            return result;
        }

        /// <summary>
        /// 判断是否是Ajax请求 
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public static bool IsAjax(this HttpRequestMessage req)
        {
            bool result = false;
            string value = req.Headers.GetValues("x-requested-with").FirstOrDefault()??"";
            result = string.IsNullOrWhiteSpace(value) && value == "XMLHttpRequest";
            return result;
        }

        /// <summary>
        /// 获取header值
        /// </summary>
        /// <param name="req"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetHeader(this HttpRequest req, string key)
        {
            string value = string.Empty;

            req.Headers.TryGetValue(key, out StringValues v);
            if (v.IsNotEmpty())
            {
                value = v.First();
            }
            return value;
        }

        public static bool IsGet(this HttpRequest request)
        {
            return "GET".Equals(request.Method, StringComparison.OrdinalIgnoreCase);
        }

        public static bool IsPost(this HttpRequest request)
        {
            return "POST".Equals(request.Method, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 获取请求的链接
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetAbsoluteUri(this HttpRequest request)
        {
            return new System.Text.StringBuilder()
                .Append(request.Scheme)
                .Append("://")
                .Append(request.Host)
                .Append(request.PathBase)
                .Append(request.Path)
                .Append(request.QueryString)
                .ToString();
        }

        /// <summary>
        /// 获取客户Ip，
        /// 注意，如果采用Nginx，需要在nginx.conf配置proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        /// startup.cs：
        /// app.UseForwardedHeaders(new ForwardedHeadersOptions  { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto});
        /// </summary>
        /// <param name = "context" ></ param >
        /// < returns ></ returns >
        public static string GetClientUserIp(this HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }

        /// <summary>
        /// 获取post请求的内容，二进制直接转字符串，小心乱码
        /// </summary>
        /// <param name="request"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public async static Task<string> GetPostContent(this HttpRequest request, Encoding encoding)
        {
            StreamReader reader = new StreamReader(request.Body, encoding);
            return await reader.ReadToEndAsync();
        }

        /// <summary>
        /// 直接获取post请求的内容
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async static Task<string> GetPostContent(this HttpRequest request)
        {
            return await request.GetPostContent(Encoding.UTF8);
        }
    }
}
